#include<iostream>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<time.h>

#define NUM 1024

using namespace std;

int main()
{
    int pipefd[2]={0};
    if(pipe(pipefd)!=0)
    {
        return 1;
    }

    pid_t id=fork();
    if(id<0)
    {
        cout<<"error"<<endl;
    }
    else if(id==0)
    {
        //子进程关闭读端
        close(pipefd[0]);
        //写入
        char mag[NUM];
        char tmp[]="hello world";
        int cnt=5;
        while(cnt--)
        {
            sprintf(mag,"时间戳：%ld,%s\n",time(nullptr),tmp);
            write(pipefd[1],mag,strlen(mag));
            sleep(1);
        }
        close(pipefd[1]);
        exit(1);
    }
    else 
    {
        //父进程关闭写端
        close(pipefd[1]);
        //读出
        char mag[NUM];
        while(1)
        {
            memset(mag,0,sizeof(mag));
            int judge=read(pipefd[0],mag,sizeof(mag)-1);
            mag[strlen(mag)]='\0';
            if(judge>0)
            {
                printf("父进程读取子进程成功：%s\n",mag);
            }
            else if(judge==0)
            {
                printf("父进程读取结束\n");
                break;
            }
            else
            {
                exit(2);
            }
        }
        close(pipefd[0]);
        int status=0;
        waitpid(id,&status,0);
        cout<<"hello code"<<endl;
    }

    return 0;
}